// findDoctor/pages/message/message.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    doctor: {},       // 医生信息
    message: [],     // 医生对患者的留言列表
    inputValue: '', // 加载状态
    userId: null  ,
    lastMsgId: null    // 当前用户ID（患者ID）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id } = options;
    const app = getApp();
    const  userId = app.globalData.userId;
    this.setData({ userId });
    this.getMessageData(id, userId);
    this.getDoctorData(id)
  },

  getDoctorData(id) {
    const app = getApp();
    const token = app.globalData.token;
    const userId = app.globalData.userId;
    
    wx.showLoading({
      title: '数据正在加载...',
    })
    wx.request({
      url: `http://localhost:8080/doctor/doctor/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}` // 添加Bearer前缀
      },
      success: (resp) => {
        console.log('医生详情数据:', resp);
        const doctor = resp.data.data;
        this.setData({
          doctor,
        })
      },
      complete: () => {
        wx.hideLoading(),
        wx.stopPullDownRefresh()
      }
    })
  },

  getMessageData(doctorId, patientId) {
    const app = getApp();
    const token = app.globalData.token;
    const userId = this.data.userId;
    wx.showLoading({
      title: '数据正在加载...',
    })
    wx.request({
      url: `http://localhost:8080/doctor/message/list`,
      method: 'GET',
      data: {
        doctorId,   // 医生ID
        patientId,  // 患者ID
      },
      header: {
        'Authorization': `Bearer ${token}` // 添加Bearer前缀
      },
      success: (resp) => {
        console.log('留言详情数据:', resp);
        const rawMessages  = resp.data.rows;
        const message = [];
        rawMessages.forEach(item => {
          if (item.messageContent) {
            message.push({
              id: `p_${item.id}`,
              sender: 'me',
              content: item.messageContent,
            });
          }
          if (item.messageReply) {
            message.push({
              id: `d_${item.id}`,
              sender: 'doctor',
              content: item.messageReply,
            });
          }
        });
        this.setData({
          message,
          lastMsgId: message.length ? message[message.length - 1].id : null
        })
        console.log('留言详情数据:', message);
      },
      complete: () => {
        wx.hideLoading(),
        wx.stopPullDownRefresh()
      }
    })
  },

  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  sendMessage() {
    const content = this.data.inputValue.trim();
    if (!content) return;

    const app = getApp();
    const doctorId = this.data.doctor.id;
    const userId = this.data.userId;

    wx.request({
      url: `http://localhost:8080/doctor/message`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`,
        'Content-Type': 'application/json'
      },
      data: {
        doctorId,
        patientId: userId,
        messageContent: content
      },
      success: (resp) => {
        console.log('发送响应:', resp);
        if (resp.statusCode === 200 && resp.data.code === 200) {
          const responseData = resp.data.data || {};
          // 追加本条消息
          const newMessage = {
            id: `p_${responseData.id || Date.now()}`,
            sender: 'me',
            content,
          };
          this.setData({
            message: [...this.data.message, newMessage],
            inputValue: '',
            lastMsgId: newMessage.id
          });
        }else {
          wx.showToast({
            title: resp.data.msg || '发送失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('发送失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})